<script setup lang="ts">
import { reactive, ref, Ref, computed, onMounted, watch } from "vue"
import { Search, Refresh } from "@element-plus/icons-vue"
import Table from "@/components/Table/index.vue"
import { propsList, terminalPropsList } from "./config"
import { useTagsViewStore } from "@/store/modules/tags-view"

import {
  getBackgroundListApi,
  getTerminalListApi,
  exportTerminalApi,
  exportBackgroundApi
} from "@/api/information/index"
import { type IInformationListData, ITerminalListData, IListParams } from "@/api/information/types/index"
import { ElMessage } from "element-plus"
import { storeToRefs } from "pinia"
import { downloadByBlobUrl } from "@/utils/index"

enum DEVICETYPE {
  INFUSION = "输液中",
  RING = "输液器呼叫",
  LACK = "输液结束（缺液）",
  LOW = "低电量"
}

enum TABSTYPE {
  BACKGROUND = "background",
  TERMINAL = "terminal"
}

interface IFrom extends IListParams {
  time: string
  event_type: number | string
  keyword: string
  data_sum: number
}

// 后台操作类型options
const backgroundTypeOptions = [
  {
    label: "新增",
    value: "add"
  },
  {
    label: "删除",
    value: "delete"
  },
  {
    label: "编辑",
    value: "update"
  },
  {
    label: "查询",
    value: "query"
  },
  {
    label: "导出",
    value: "export"
  },
  {
    label: "登出",
    value: "logout"
  },
  {
    label: "登入",
    value: "login"
  },
  {
    label: "升级",
    value: "upgrade"
  }
]

// 设备操作类型options
const deviceTypeOptions = [
  {
    label: "输液中",
    value: 1
  },
  {
    label: "输液器呼叫",
    value: 2
  },
  {
    label: "输液结束（缺液）",
    value: 3
  },
  {
    label: "低电量",
    value: 4
  }
]
const tableRef: Ref<typeof Table | null> = ref(null)
const tableData = ref<IInformationListData[] | ITerminalListData[]>([])
const selectedData = ref<IInformationListData[] | ITerminalListData[]>([])
const tagsViewStore = useTagsViewStore()

const { partition } = storeToRefs(tagsViewStore)

const activeName = ref(TABSTYPE.BACKGROUND)

const tabsType = computed(() => {
  return activeName.value === TABSTYPE.BACKGROUND
})

const backgroundSelectOptions = ref(backgroundTypeOptions)
const deviceSelectOptions = ref(deviceTypeOptions)
const defaultTime: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)] // '12:00:00', '08:00:00'
const searchParamsForm = reactive<IFrom>({
  page_index: 1,
  page_size: 10,
  data_sum: 0,
  keyword: "",
  time: "",
  event_type: ""
})

watch(
  () => partition.value,
  () => {
    getDataList()
  }
)

const getDataList = async () => {
  const { keyword, time, event_type, page_size, page_index } = searchParamsForm
  const start_time = time ? time[0] : ""
  const end_time = time ? time[1] : ""
  const params = {
    page_size,
    page_index,
    device_type_id: 1,
    keyword,
    start_time,
    end_time,
    event_type,
    area_id: partition.value
  }

  const res = tabsType.value ? await getBackgroundListApi(params) : await getTerminalListApi(params)
  const { result, data, return_message } = res
  if (result === 200) {
    const { data: tableListData, data_sum, page_size, page_index } = data

    tableData.value = tableListData
    searchParamsForm.data_sum = data_sum ?? 0
    searchParamsForm.page_size = page_size ?? 10
    searchParamsForm.page_index = page_index ?? 1
  } else {
    ElMessage.error(return_message)
  }
}

const handleSearch = () => {
  searchParamsForm.page_index = 1
  searchParamsForm.page_size = 10
  getDataList()
}

const handleChangePage = (page: number) => {
  searchParamsForm.page_index = page
  getDataList()
}

const handleChangeSize = (size: number) => {
  searchParamsForm.page_size = size
  getDataList()
}

const handleSelect = (selectData: IInformationListData[] | ITerminalListData[]) => {
  selectedData.value = selectData
}

const resetSearch = () => {
  searchParamsForm.keyword = ""
  searchParamsForm.event_type = ""
  searchParamsForm.time = ""
  getDataList()
}

const handleChangeTabs = () => {
  console.info(activeName.value)
  tableRef.value?.clearSelected()
  getDataList()
}

const handleExportLog = async () => {
  const { keyword, time, event_type } = searchParamsForm
  const start_time = time ? time[0] : ""
  const end_time = time ? time[1] : ""
  const idarr = selectedData.value.map((item) => item.id)
  const params = {
    device_type_id: 1,
    keyword,
    event_type,
    start_time,
    end_time,
    area_id: partition.value,
    idarr
  }
  const res = tabsType.value ? await exportBackgroundApi(params) : await exportTerminalApi(params)
  //todo
  downloadByBlobUrl(res, tabsType.value ? "后台系统日志" : "终端系统日志", res.type)
}

const eventText = (type: number) => {
  let text = ""
  switch (type) {
    case 1:
      text = DEVICETYPE.INFUSION
      break
    case 2:
      text = DEVICETYPE.RING
      break
    case 3:
      text = DEVICETYPE.LACK
      break
    case 4:
      text = DEVICETYPE.LOW
      break
  }
  return text
}

onMounted(() => {
  getDataList()
})
</script>

<template>
  <div>
    <!-- 搜索框 -->
    <div flex justify-between bg-white items-center px-15px pt-5px rounded-5px mb-15px>
      <div>
        <el-tabs v-model="activeName" @tab-change="handleChangeTabs">
          <el-tab-pane label="后台系统日志" name="background" />
          <el-tab-pane label="终端系统日志" name="terminal" />
        </el-tabs>
      </div>

      <div flex items-center>
        <el-form ref="searchFormRef" :inline="true" :model="searchParamsForm">
          <el-form-item prop="username">
            <el-date-picker
              v-model="searchParamsForm.time"
              type="datetimerange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY/MM/DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              :default-time="defaultTime"
            />
          </el-form-item>

          <el-form-item prop="keyword">
            <el-input
              v-model="searchParamsForm.keyword"
              :placeholder="tabsType ? '请输入账号/姓名' : '请输入设备名称/呼叫码'"
            />
          </el-form-item>

          <el-form-item prop="num">
            <el-select
              clearable
              v-model="searchParamsForm.event_type"
              :placeholder="tabsType ? '请选择操作类型' : '请选择事件类型'"
              style="width: 240px"
            >
              <el-option
                v-for="item in tabsType ? backgroundSelectOptions : deviceSelectOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" class="bg-#387af6!" :icon="Search" @click="handleSearch">查询</el-button>
            <el-button type="primary" :icon="Refresh" class="bg-#387af6!" @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>

        <el-button class="text-#000000d9!" :disabled="!selectedData.length" @click="handleExportLog"
          >导出日志</el-button
        >
      </div>
    </div>

    <!-- 表格 -->
    <div>
      <Table
        ref="tableRef"
        :index="true"
        :select-width="60"
        :total="searchParamsForm.data_sum"
        :show-check-box="true"
        :data="tableData"
        :propsList="tabsType ? propsList : terminalPropsList"
        @change-page="handleChangePage"
        @change-size="handleChangeSize"
        @select="handleSelect"
      >
        <template #event_type="{ row }">
          <div>
            <span>{{ eventText(row.event_type) }}</span>
          </div>
        </template>
      </Table>
    </div>
  </div>
</template>

<style lang="scss" scoped>
:deep(.el-form-item) {
  margin-bottom: 0px;
}
</style>
